
package com.chongchong.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chongchong.common.constant.CommonConstant;
import com.chongchong.common.constant.StaticConstant;
import com.chongchong.common.tool.EmailCommonUtil;
import com.chongchong.core.tool.utils.*;
import com.chongchong.user.entity.User;
import com.chongchong.user.entity.UserInfo;
import com.chongchong.user.entity.UserOauth;
import com.chongchong.user.excel.UserExcel;
import com.chongchong.user.mapper.UserMapper;
import com.chongchong.user.service.IUserOauthService;
import com.chongchong.user.service.IUserService;
import com.chongchong.user.vo.UserSuperVo;
import com.chongchong.core.log.exception.ServiceException;
import com.chongchong.core.tool.api.R;
import com.chongchong.system.entity.Tenant;
import com.chongchong.system.feign.ISysClient;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 服务实现类
 *
 * @author
 */
@Service("userService")
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
	private static final String GUEST_NAME = "guest";
	private static final String MINUS_ONE = "-1";

	private ISysClient sysClient;
	private IUserOauthService userOauthService;
	@Autowired
	EmailCommonUtil emailCommonUtil;
	@Override
	public boolean submit(User user) {
		Long cnt = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, user.getTenantId()).eq(User::getAccount, user.getAccount()));
		if (cnt > 0) {
			throw new ServiceException("当前用户已存在!");
		}
		Date date = new Date();
		//若是新增用户填写密码更新时间字段，用于判断密码过期的重要参数
		if(user.getId() == null){
			String password = PasswordUtils.randomPW();
			user.setPassword(password);
			user.setPasswordUpdate(date);
			//若用户昵称为空，将用户真名复制给昵称
			if(!Func.isNotEmpty(user.getName())){
				user.setName(user.getRealName());
			}
			String email = user.getEmail();
			if(!StringUtils.isEmpty(email)){
				List<String> userEmails = new ArrayList<>();
				userEmails.add(email);
				emailCommonUtil.sendMail(userEmails, StaticConstant.USER_PASSWORD_EMAIL_THEME, StaticConstant.USER_PASSWORD_EMAIL_TITLE, StaticConstant.USER_PASSWORD_EMAIL_CONTENT + password);
			}
		}
		if (Func.isNotEmpty(user.getPassword())) {
			user.setPassword(DigestUtil.encrypt(user.getPassword()));
		}
		user.setCreateTime(date);
		return saveOrUpdate(user);
	}

	@Override
	public IPage<User> selectUserPage(IPage<User> page, User user) {
		return page.setRecords(baseMapper.selectUserPage(page, user));
	}

	@Override
	public UserInfo userInfo(Long userId) {
		UserInfo userInfo = new UserInfo();
		User user = baseMapper.selectById(userId);
		userInfo.setUser(user);
		if (Func.isNotEmpty(user)) {
			List<String> roleAlias = baseMapper.getRoleAlias(Func.toStrArray(user.getRoleId()));
			userInfo.setRoles(roleAlias);
			List<String> roleName = baseMapper.getRoleName(Func.toStrArray(user.getRoleId()));
			userInfo.setRoleNames(roleName);
		}
		return userInfo;
	}
	@Override
	public UserInfo userInfo(String tenantId, String account) {
		User user = baseMapper.getUserByAccount(tenantId,account);
		UserInfo userInfo = new UserInfo();
		userInfo.setUser(user);
		if (Func.isNotEmpty(user)) {
			List<String> roleAlias = baseMapper.getRoleAlias(Func.toStrArray(user.getRoleId()));
			userInfo.setRoles(roleAlias);
			List<String> roleName = baseMapper.getRoleName(Func.toStrArray(user.getRoleId()));
			userInfo.setRoleNames(roleName);
		}
		return userInfo;
	}
	@Override
	public UserInfo userInfo(String tenantId, String account, String password) {
		UserInfo userInfo = new UserInfo();
		User user = baseMapper.getUser(tenantId, account, password);
		userInfo.setUser(user);
		if (Func.isNotEmpty(user)) {
			List<String> roleAlias = baseMapper.getRoleAlias(Func.toStrArray(user.getRoleId()));
			userInfo.setRoles(roleAlias);
			List<String> roleName = baseMapper.getRoleName(Func.toStrArray(user.getRoleId()));
			userInfo.setRoleNames(roleName);
		}
		return userInfo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public UserInfo userInfo(UserOauth userOauth) {
		UserOauth uo = userOauthService.getOne(Wrappers.<UserOauth>query().lambda().eq(UserOauth::getUuid, userOauth.getUuid()).eq(UserOauth::getSource, userOauth.getSource()));
		UserInfo userInfo;
		if (Func.isNotEmpty(uo) && Func.isNotEmpty(uo.getUserId())) {
			userInfo = this.userInfo(uo.getUserId());
			userInfo.setOauthId(Func.toStr(uo.getId()));
		} else {
			userInfo = new UserInfo();
			if (Func.isEmpty(uo)) {
				userOauthService.save(userOauth);
				userInfo.setOauthId(Func.toStr(userOauth.getId()));
			} else {
				userInfo.setOauthId(Func.toStr(uo.getId()));
			}
			User user = new User();
			user.setAccount(userOauth.getUsername());
			userInfo.setUser(user);
			userInfo.setRoles(Collections.singletonList(GUEST_NAME));
		}
		return userInfo;
	}

	@Override
	public boolean grant(String userIds, String roleIds) {
		User user = new User();
		user.setRoleId(roleIds);
		return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
	}

	@Override
	public boolean resetPassword(String userIds) {
		User user = new User();
		user.setPassword(DigestUtil.encrypt(CommonConstant.DEFAULT_PASSWORD));
		Date now = DateUtil.now();
		user.setUpdateTime(now);
		user.setPasswordUpdate(now);
		return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
	}

	@Override
	public boolean updatePassword(Long userId, String oldPassword, String newPassword, String newPassword1) {
		User user = getById(userId);
		if (!newPassword.equals(newPassword1)) {
			throw new ServiceException("请输入正确的确认密码!");
		}
		if (!user.getPassword().equals(DigestUtil.encrypt(oldPassword))) {
			throw new ServiceException("原密码不正确!");
		}
		Date now = DateUtil.now();
		return this.update(Wrappers.<User>update().lambda().set(User::getPassword, DigestUtil.encrypt(newPassword)).set(User::getPasswordUpdate,now).set(User::getUpdateTime,now).eq(User::getId, userId));
	}

	@Override
	public List<String> getRoleName(String roleIds) {
		return baseMapper.getRoleName(Func.toStrArray(roleIds));
	}
	@Override
	public List<User> getUserByRoleIds(String roleIds){
		return baseMapper.getUserByRoleIds(Func.toStrArray(roleIds));
	}

	@Override
	public List<String> getDeptName(String deptIds) {
		return baseMapper.getDeptName(Func.toStrArray(deptIds));
	}

	@Override
	public void importUser(List<UserExcel> data) {
		data.forEach(userExcel -> {
			User user = Objects.requireNonNull(BeanUtil.copy(userExcel, User.class));
			/*// 设置部门ID
			user.setDeptId(sysClient.getDeptIds(userExcel.getTenantId(), userExcel.getDeptName()));
			// 设置岗位ID
			user.setPostId(sysClient.getPostIds(userExcel.getTenantId(), userExcel.getPostName()));*/
			// 设置角色ID
			user.setRoleId(sysClient.getRoleIds(userExcel.getTenantId(), userExcel.getRoleName()));
			// 设置默认密码
			user.setPassword(CommonConstant.DEFAULT_PASSWORD);
			this.submit(user);
		});
	}

	@Override
	public List<UserExcel> exportUser(Wrapper<User> queryWrapper) {
		List<UserExcel> userList = baseMapper.exportUser(queryWrapper);
		userList.forEach(user -> {
			user.setRoleName(StringUtil.join(sysClient.getRoleNames(user.getRoleId())));
			user.setDeptName(StringUtil.join(sysClient.getDeptNames(user.getDeptId())));
			user.setPostName(StringUtil.join(sysClient.getPostNames(user.getPostId())));
		});
		return userList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean registerGuest(User user, Long oauthId) {
		R<Tenant> result = sysClient.getTenant(user.getTenantId());
		Tenant tenant = result.getData();
		if (!result.isSuccess() || tenant == null || tenant.getId() == null) {
			throw new ServiceException("租户信息错误!");
		}
		UserOauth userOauth = userOauthService.getById(oauthId);
		if (userOauth == null || userOauth.getId() == null) {
			throw new ServiceException("第三方登陆信息错误!");
		}
		user.setRealName(user.getName());
		/*user.setAvatar(userOauth.getAvatar());*/
		user.setRoleId(MINUS_ONE);
		/*user.setDeptId(MINUS_ONE);
		user.setPostId(MINUS_ONE);*/
		boolean userTemp = this.submit(user);
		userOauth.setUserId(user.getId());
		userOauth.setTenantId(user.getTenantId());
		boolean oauthTemp = userOauthService.updateById(userOauth);
		return (userTemp && oauthTemp);
	}

	/**根据当前用户查询所有上级用户信息(sql方式)
	 * @description: 根据当前用户查询所有上级用户信息(sql方式)
	 * @param: id
	 * @return: UserSuperVo
	 * @author wuning
	 * @date: 2022/8/31 15:46
	 */
	@Override
	public UserSuperVo selectUserSuperList(Long id) {
		return baseMapper.selectUserSuperList(id);
	}
	/** 根据当前用户查询所有上级用户信息(递归方式)
	 * @description:  根据当前用户查询所有上级用户信息(递归方式)
	 * @param: id
	 * @param: tier 层级
	 * @return: UserSuperVo
	 * @author wuning
	 * @date: 2022/8/31 17:16
	 */
	@Override
	public UserSuperVo selectAllUserSuperList(Long id,Integer tier) {
		List<UserSuperVo> userSuperVos = baseMapper.selectAllUserSuperList();
		UserSuperVo currentUser = null;
		if(userSuperVos != null && userSuperVos.size() > 0){
			for (UserSuperVo userSuperVo : userSuperVos) {
				if(id.equals(userSuperVo.getId())){
					currentUser = userSuperVo;
					break;
				}
			}
			if(currentUser != null){
				recursionUser(currentUser,userSuperVos,tier);
			}
		}
		return currentUser;
	}

	/**
	 * 查询库中所有表
	 *
	 * @param
	 * @return java.util.List<java.lang.String>
	 * @author wuning
	 * @date 2022/9/29 17:50
	 */
	@Override
	public List<String> selectTableNameList() {
		return baseMapper.selectTableNameList();
	}
	/**
	 * 修改库中所有表的字符集utf8mb4 字段为 utf8mb4_0900_ai_ci
	 *
	 * @param
	 * @return java.util.List<java.lang.String>
	 * @author wuning
	 * @date 2022/9/29 17:50
	 */
	@Override
	public void updateTableNameUtf8mb4(String tableName) {
		baseMapper.updateTableNameUtf8mb4(tableName);
	}

	/**递归方式获取当前用户所有上级用户信息
	 * @description: 递归方式获取当前用户所有上级用户信息
	 * @param: currentUser 当前用户
	 * @param: userSuperVos 所有用户
	 * @param: tier 层级
	 * @return: void
	 * @author wuning
	 * @date: 2022/9/1 09:48
	 */
	private void recursionUser(UserSuperVo currentUser, List<UserSuperVo> userSuperVos,Integer tier) {
		Long parentId = currentUser.getParentId();
		if (tier == null || tier == 0) {
			return;
		}
		tier--;
		if (parentId != null) {
			for (UserSuperVo userSuperVo : userSuperVos) {
				if (parentId.equals(userSuperVo.getId())) {
					currentUser.setSuperUser(userSuperVo);
					if (userSuperVo.getParentId() != null) {
						recursionUser(userSuperVo, userSuperVos,tier);
					} else {
						userSuperVo.setSuperUser(null);
					}
					break;
				}
			}
		}

	}
}
